from rest_framework import serializers
from django_redis import get_redis_connection
from redis import RedisError
import logging
"""
序列化器校验方式
1, 字段校验
2, 参数选项校验
3, 单个字段校验
4, 多字段校验
"""
#获取日志记录器
logger = logging.getLogger("django")

class RegisterSMSCodeSerializer(serializers.Serializer):

    text = serializers.CharField(label="图片验证码",min_length=4,max_length=4)
    image_code_id = serializers.UUIDField(label="图片验证码编号")

    def validate(self, attrs):
        #1,获取图片验证码,编号
        text = attrs["text"]
        image_code_id = attrs["image_code_id"]

        #2,通过图片验证码编号,取出redis图片验证码
        redis_conn = get_redis_connection("code") #获取settings中配置的redis连接
        redis_text = redis_conn.get("img_%s"%image_code_id)

        #3,判断是否过期
        if not redis_text:
            raise serializers.ValidationError("图片验证码过期")

        #4,删除图片验证码
        try:
            redis_conn.delete("img_%s"%image_code_id)
        except RedisError as e:
            logger.error(e)

        #5,判断图片验证码的正确性
        if text.lower() != redis_text.decode().lower():
            raise serializers.ValidationError("图片验证码错误")

        #6,返回
        return attrs